package com.yupi.springbootinit.utils;


import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
public class ExcelUtil {
    public static String excelToCSV(MultipartFile multipartFile) throws IOException {
//        File file = null;
//        try{
//            file = ResourceUtils.getFile("classpath:网站数据.xlsx");
//        }catch (Exception e){
//            log.error(e.getMessage());
//        }

        List<Map<Integer,String>> list = EasyExcel.read(multipartFile.getInputStream()).excelType(ExcelTypeEnum.XLSX)
                .sheet().headRowNumber(0).doReadSync();

        if(CollUtil.isEmpty(list)){
            return "";
        }
        // 原始数据压缩
        //[{0=日期, 1=用户数, 2=null, 3=null}, {0=1, 1=10, 2=null, 3=null}, {0=2, 1=20}, {0=3, 1=30}]
        // 存在为null数据，过滤
        StringBuilder stringBuilder = new StringBuilder();
        Map<Integer, String> header = list.get(0);
        List<String> collect = header.values().stream().filter(ObjectUtils::isNotEmpty).collect(Collectors.toList());
        String join = StringUtils.join(collect, ",");
        stringBuilder.append(join).append("\n");
        //System.out.println(join);

        for(int i=1;i<list.size();i++){
            Map<Integer,String> map = list.get(i);
            List<String> list1 = map.values().stream().filter(ObjectUtils::isNotEmpty).collect(Collectors.toList());
            stringBuilder.append(StringUtils.join(list1, ",")).append("\n");
            //System.out.println(StringUtils.join(list1, ","));
        }
        System.out.println(stringBuilder.toString());
        System.out.println("===================");
        System.out.println(list);
        return stringBuilder.toString();
    }

//    public static void main(String[] args) throws FileNotFoundException {
//        excelToCSV(null);
//    }
}
